package com.example.bigwork.service.impl;

import com.example.bigwork.dto.request.ProductCreateRequest;
import com.example.bigwork.dto.response.ProductResponse;
import com.example.bigwork.entity.Product;
import com.example.bigwork.enums.ProductCategory;
import com.example.bigwork.exception.ResourceNotFoundException;
import com.example.bigwork.mapper.ProductMapper;
import com.example.bigwork.service.ProductService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ProductServiceImpl implements ProductService {

    private final ProductMapper productMapper;

    @Autowired
    public ProductServiceImpl(ProductMapper productMapper) {
        this.productMapper = productMapper;
    }

    @Override
    @Transactional
    public ProductResponse addProduct(ProductCreateRequest createRequest) {
        Product product = new Product();
        BeanUtils.copyProperties(createRequest, product);
        product.setCreatedAt(LocalDateTime.now());
        product.setUpdatedAt(LocalDateTime.now());

        productMapper.insertProduct(product); // Assumes insertProduct sets the ID back

        ProductResponse response = new ProductResponse();
        BeanUtils.copyProperties(product, response);
        return response;
    }

    @Override
    public ProductResponse getProductById(Long id) {
        Product product = findProductEntityById(id);
        ProductResponse response = new ProductResponse();
        BeanUtils.copyProperties(product, response);
        return response;
    }

    @Override
    public Product findProductEntityById(Long id) {
        return productMapper.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("Product not found with ID: " + id));
    }

    @Override
    public List<ProductResponse> searchProductsByName(String name) {
        List<Product> products = productMapper.findByNameContaining(name);
        return products.stream().map(product -> {
            ProductResponse response = new ProductResponse();
            BeanUtils.copyProperties(product, response);
            return response;
        }).collect(Collectors.toList());
    }

    @Override
    public List<ProductResponse> getProductsByCategory(ProductCategory category) {
        List<Product> products = productMapper.findByCategory(category);
        return products.stream().map(product -> {
            ProductResponse response = new ProductResponse();
            BeanUtils.copyProperties(product, response);
            return response;
        }).collect(Collectors.toList());
    }
}
